/**
 * 简化版汉字笔顺动画适配器
 * 专为 uni-app 环境设计
 */

// 全局实例
let writerInstance = null;

// 初始化笔顺动画
export function initWriter(canvasId, character, options = {}) {
  // 默认配置
  const defaultOptions = {
    width: 200,
    height: 200,
    strokeColor: '#333',
    delayBetweenStrokes: 500
  };
  
  // 合并配置
  const mergedOptions = { ...defaultOptions, ...options };
  
  return new Promise((resolve, reject) => {
    try {
      // 获取 canvas 上下文
      const ctx = uni.createCanvasContext(canvasId);
      
      if (!ctx) {
        console.error('无法获取 canvas 上下文');
        reject(new Error('无法获取 canvas 上下文'));
        return;
      }
      
      // 创建笔顺动画实例
      writerInstance = {
        character,
        options: mergedOptions,
        ctx,
        canvasId,
        isAnimating: false,
        animationTimer: null,
        
        // 绘制静态汉字
        drawCharacter() {
          // 清空画布
          ctx.clearRect(0, 0, mergedOptions.width, mergedOptions.height);
          
          // 绘制汉字
          ctx.font = `${mergedOptions.width * 0.8}px sans-serif`;
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          ctx.fillStyle = mergedOptions.strokeColor;
          ctx.fillText(character, mergedOptions.width / 2, mergedOptions.height / 2);
          
          // 显示绘制内容
          ctx.draw();
        },
        
        // 播放笔顺动画
        animateCharacter() {
          // 如果已经在播放，则返回
          if (this.isAnimating) return true;
          
          // 设置动画状态
          this.isAnimating = true;
          
          // 清空画布
          ctx.clearRect(0, 0, mergedOptions.width, mergedOptions.height);
          ctx.draw();
          
          // 显示提示
          uni.showToast({
            title: '正在播放笔顺动画',
            icon: 'none',
            duration: 2000
          });
          
          // 获取笔画数据
          const strokes = getStrokesForCharacter(character, mergedOptions);
          
          // 逐笔画绘制
          this.drawStrokesSequentially(strokes, 0);
          
          return true;
        },
        
        // 逐笔画绘制
        drawStrokesSequentially(strokes, index) {
          // 检查是否结束
          if (index >= strokes.length || !this.isAnimating) {
            this.isAnimating = false;
            return;
          }
          
          // 获取当前笔画
          const stroke = strokes[index];
          
          // 绘制当前笔画
          ctx.lineWidth = 8;
          ctx.lineCap = 'round';
          ctx.lineJoin = 'round';
          ctx.strokeStyle = mergedOptions.strokeColor;
          
          ctx.beginPath();
          ctx.moveTo(stroke[0].x, stroke[0].y);
          
          for (let i = 1; i < stroke.length; i++) {
            ctx.lineTo(stroke[i].x, stroke[i].y);
          }
          
          ctx.stroke();
          ctx.draw(true); // 保留之前的绘制内容
          
          // 设置下一笔画的定时器
          this.animationTimer = setTimeout(() => {
            this.drawStrokesSequentially(strokes, index + 1);
          }, mergedOptions.delayBetweenStrokes);
        },
        
        // 描红练习
        quiz(callbacks) {
          // 停止任何正在进行的动画
          this.stopAnimation();
          
          // 清空画布
          ctx.clearRect(0, 0, mergedOptions.width, mergedOptions.height);
          
          // 绘制淡色汉字作为描红背景
          ctx.font = `${mergedOptions.width * 0.8}px sans-serif`;
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          ctx.setGlobalAlpha(0.2);
          ctx.fillStyle = mergedOptions.strokeColor;
          ctx.fillText(character, mergedOptions.width / 2, mergedOptions.height / 2);
          ctx.setGlobalAlpha(1.0);
          
          // 显示绘制内容
          ctx.draw();
          
          // 显示描红提示
          uni.showToast({
            title: '请在汉字上描红',
            icon: 'none',
            duration: 2000
          });
          
          // 模拟完成回调
          setTimeout(() => {
            if (callbacks && callbacks.onComplete) {
              callbacks.onComplete();
            }
          }, 5000);
          
          return true;
        },
        
        // 取消描红练习
        cancelQuiz() {
          // 停止任何正在进行的动画
          this.stopAnimation();
          
          // 重新绘制静态汉字
          this.drawCharacter();
          
          return true;
        },
        
        // 停止动画
        stopAnimation() {
          if (this.animationTimer) {
            clearTimeout(this.animationTimer);
            this.animationTimer = null;
          }
          this.isAnimating = false;
        },
        
        // 销毁实例
        destroy() {
          this.stopAnimation();
          ctx.clearRect(0, 0, mergedOptions.width, mergedOptions.height);
          ctx.draw();
          return true;
        }
      };
      
      // 初始绘制
      writerInstance.drawCharacter();
      
      resolve(writerInstance);
    } catch (error) {
      console.error('初始化失败:', error);
      reject(error);
    }
  });
}

// 获取汉字的笔画数据
function getStrokesForCharacter(character, options) {
  const width = options.width;
  const height = options.height;
  const center = { x: width / 2, y: height / 2 };
  const size = Math.min(width, height) * 0.7;
  
  // 预定义的笔画数据
  const strokesData = {
    '一': [
      [
        { x: center.x - size/2, y: center.y },
        { x: center.x + size/2, y: center.y }
      ]
    ],
    '二': [
      [
        { x: center.x - size/2, y: center.y - size/4 },
        { x: center.x + size/2, y: center.y - size/4 }
      ],
      [
        { x: center.x - size/2, y: center.y + size/4 },
        { x: center.x + size/2, y: center.y + size/4 }
      ]
    ],
    '三': [
      [
        { x: center.x - size/2, y: center.y - size/3 },
        { x: center.x + size/2, y: center.y - size/3 }
      ],
      [
        { x: center.x - size/2, y: center.y },
        { x: center.x + size/2, y: center.y }
      ],
      [
        { x: center.x - size/2, y: center.y + size/3 },
        { x: center.x + size/2, y: center.y + size/3 }
      ]
    ],
    '口': [
      [
        { x: center.x - size/3, y: center.y - size/3 },
        { x: center.x + size/3, y: center.y - size/3 }
      ],
      [
        { x: center.x + size/3, y: center.y - size/3 },
        { x: center.x + size/3, y: center.y + size/3 }
      ],
      [
        { x: center.x + size/3, y: center.y + size/3 },
        { x: center.x - size/3, y: center.y + size/3 }
      ],
      [
        { x: center.x - size/3, y: center.y + size/3 },
        { x: center.x - size/3, y: center.y - size/3 }
      ]
    ]
  };
  
  // 返回预定义的笔画数据，如果没有则返回默认十字
  return strokesData[character] || [
    [
      { x: center.x - size/2, y: center.y },
      { x: center.x + size/2, y: center.y }
    ],
    [
      { x: center.x, y: center.y - size/2 },
      { x: center.x, y: center.y + size/2 }
    ]
  ];
}

// 播放笔顺动画
export function animateCharacter() {
  if (writerInstance && typeof writerInstance.animateCharacter === 'function') {
    return writerInstance.animateCharacter();
  }
  return false;
}

// 开始描红练习
export function startQuiz(callbacks = {}) {
  if (writerInstance && typeof writerInstance.quiz === 'function') {
    return writerInstance.quiz(callbacks);
  }
  return false;
}

// 取消描红练习
export function cancelQuiz() {
  if (writerInstance && typeof writerInstance.cancelQuiz === 'function') {
    return writerInstance.cancelQuiz();
  }
  return false;
}

// 销毁实例
export function destroyWriter() {
  if (writerInstance && typeof writerInstance.destroy === 'function') {
    const result = writerInstance.destroy();
    writerInstance = null;
    return result;
  }
  return false;
}

// 获取当前实例
export function getWriter() {
  return writerInstance;
} 